import time
import sys
import threading


class AIGCProgressBar:
    def __init__(self):
        """初始化进度条"""
        self.running = False
        self.thread = None
        self.start_time = 0
        self.elapsed_seconds = 0

    def start(self):
        """启动进度条"""
        if self.running:
            return

        self.running = True
        self.start_time = time.time()

        # 创建并启动进度条线程
        self.thread = threading.Thread(target=self._update_progress)
        self.thread.daemon = True
        self.thread.start()

    def stop(self):
        """停止进度条"""
        if not self.running:
            return

        self.running = False
        if self.thread:
            self.thread.join(timeout=0.5)

        # 显示最终状态
        sys.stdout.write("\rAIGC请求中，请静待返回 [{}>     ] {:2d}s\n请求完成！\n"
                         .format("=" * self.elapsed_seconds, self.elapsed_seconds))
        sys.stdout.flush()

    def _update_progress(self):
        """更新进度条内容"""
        print("AIGC请求中，请静待返回", end='', flush=True)

        while self.running:
            # 计算经过的秒数
            self.elapsed_seconds = int(time.time() - self.start_time)

            # 更新显示
            sys.stdout.write("\rAIGC请求中，请静待返回 [{}>     ] {:2d}s"
                             .format("=" * self.elapsed_seconds, self.elapsed_seconds))
            sys.stdout.flush()

            # 等待0.1秒以减少CPU占用
            time.sleep(0.1)